package com.ruoyi.quartz.task.wheather;

import com.ruoyi.yanjing.domain.WeatherForecast;
import com.ruoyi.yanjing.gaode.GaoDeApi;
import com.ruoyi.yanjing.gaode.constant.WeatherConstant;
import com.ruoyi.yanjing.gaode.constant.WeatherType;
import com.ruoyi.yanjing.gaode.model.Forecast;
import com.ruoyi.yanjing.gaode.model.GaoDeResult;
import com.ruoyi.yanjing.service.IWeatherForecastService;
import com.ruoyi.yanjing.service.IWeatherService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Component("autoPullGaoDeForecastWeatherJob")
public class AutoPullGaoDeForecastWeatherJob implements Runnable {

    private static final Log log = LogFactory.getLog(AutoPullGaoDeForecastWeatherJob.class);


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IWeatherForecastService weatherForecastService;


    /**
     * 北京市
     * 城市编码表：doc/AMap_adcode_citycode.xlsx
     */
    private static final String AD_CODE = "110000";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run() {

        log.info("Pull forecast weather data begin==================>");
        long startTime = System.currentTimeMillis();

        // 拉取预报天气
        this.saveForecast(AD_CODE);

        long endTime = System.currentTimeMillis();
        log.info("spend time:" + (endTime - startTime));
        log.info("Pull forecast weather data end<==================");
    }

    /**
     * 预报天气
     *
     * @param adcode
     */
    private void saveForecast(String adcode) {
        StringBuilder sendUrl = new StringBuilder(WeatherConstant.WEATHER_URL)
                .append("?key=").append(GaoDeApi.KEY_VALUE)
                .append("&city=").append(adcode)
                .append("&extensions=all");
        ResponseEntity<GaoDeResult> responseEntity = restTemplate.getForEntity(sendUrl.toString(), GaoDeResult.class);
        // 请求异常，可能由于网络等原因
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            log.info("Request for Gaode interface error");
            return;
        }

        // 请求失败
        GaoDeResult gaoDeResult = responseEntity.getBody();
        String status = gaoDeResult.getStatus();
        if (!status.equals(GaoDeApi.SUCCESS)) {
            log.info("Request for Gaode interface failed");
            return;
        }

        List<Forecast> forecasts = gaoDeResult.getForecasts();
        if (CollectionUtils.isEmpty(forecasts)) {
            return;
        }

        // 预报天气
        Forecast forecast = forecasts.get(0);
        List<WeatherForecast> weatherForecastList = new ArrayList<>();
        List<Forecast.Cast> casts = forecast.getCasts();
        for (Forecast.Cast cast : casts) {
            WeatherForecast weatherForecast = new WeatherForecast();
            weatherForecast.setProvince(forecast.getProvince());
            weatherForecast.setCity(forecast.getCity());
            weatherForecast.setAdcode(forecast.getAdcode());
            weatherForecast.setDate(cast.getDate());
            weatherForecast.setWeek(cast.getWeek());
            weatherForecast.setDayWeather(cast.getDayweather());
            weatherForecast.setDayWeatherImg(WeatherType.getCodeByDes(cast.getDayweather()));
            weatherForecast.setNightWeather(cast.getNightweather());
            weatherForecast.setNightWeatherImg(WeatherType.getCodeByDes(cast.getNightweather()));
            weatherForecast.setDayTemp(cast.getDaytemp());
            weatherForecast.setNightTemp(cast.getNighttemp());
            weatherForecast.setDayWind(cast.getDaywind());
            weatherForecast.setNightWind(cast.getNightwind());
            weatherForecast.setDayPower(cast.getDaypower());
            weatherForecast.setNightPower(cast.getNightpower());
            weatherForecast.setReportTime(forecast.getReporttime());
            weatherForecastList.add(weatherForecast);
            weatherForecastService.insertWeatherForecast(weatherForecast);

        }
    }
}
